// 通用工具函数 - 增强版

// 格式化日期 - 兼容性增强
function formatDate(dateString) {
  if (!dateString) return '';

  // 1. 处理 Excel 数字日期 (例如 44927.5)
  if (typeof dateString === 'number' || (!isNaN(parseFloat(dateString)) && isFinite(dateString) && !String(dateString).includes('-') && !String(dateString).includes('/'))) {
    const serial = parseFloat(dateString);
    // 简单的阈值判断 (Excel日期通常 > 20000，对应 1954年以后)
    if (serial > 20000 && serial < 2958465) {
      const utcDays = Math.floor(serial - 25569);
      const utcValue = utcDays * 86400000;
      const dateInfo = new Date(utcValue);

      const fractionalDay = serial - Math.floor(serial) + 0.0000001;
      const totalSeconds = Math.floor(86400 * fractionalDay);
      const seconds = totalSeconds % 60;
      const hours = Math.floor(totalSeconds / 3600);
      const minutes = Math.floor(totalSeconds / 60) % 60;

      const date = new Date(dateInfo.getFullYear(), dateInfo.getMonth(), dateInfo.getDate(), hours, minutes, seconds);
      return formatJsDate(date);
    }
  }

  let str = String(dateString).trim();
  if (!str) return '';

  // 2. 处理纯数字 YYYYMMDD (例如 20230512)
  if (/^\d{8}$/.test(str)) {
    return `${str.substr(0, 4)}/${str.substr(4, 2)}/${str.substr(6, 2)} 00:00:00`;
  }

  // 3. 处理 YYYYMMDDHHmmss
  if (/^\d{14}$/.test(str)) {
    return `${str.substr(0, 4)}/${str.substr(4, 2)}/${str.substr(6, 2)} ${str.substr(8, 2)}:${str.substr(10, 2)}:${str.substr(12, 2)}`;
  }

  // 4. 处理包含中文的 (2023年5月12日)
  str = str.replace(/年|月/g, '/').replace(/日/g, ' ');

  // 5. 尝试标准解析
  const d = new Date(str);
  if (!isNaN(d.getTime())) {
    return formatJsDate(d);
  }

  return str; // 无法解析则原样返回
}

// 辅助：格式化 JS Date 对象为 YYYY/MM/DD HH:mm:ss
function formatJsDate(date) {
  const pad = n => n.toString().padStart(2, '0');
  const year = date.getFullYear();
  const month = pad(date.getMonth() + 1);
  const day = pad(date.getDate());
  const hours = pad(date.getHours());
  const minutes = pad(date.getMinutes());
  const seconds = pad(date.getSeconds());
  return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
}

const Validators = {
  isPhone: (str) => /^1[3-9]\d{9}$/.test(String(str).trim()),
  isIdCard: (str) => /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(String(str).trim()),
  isNumber: (str) => !isNaN(parseFloat(str)) && isFinite(str),
  isRequired: (str) => str !== null && str !== undefined && String(str).trim() !== ''
};

function timeDiff(date1, date2) {
  const diffMs = Math.abs(new Date(date2) - new Date(date1));
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
  return diffDays;
}

function deepClone(obj) {
  return JSON.parse(JSON.stringify(obj));
}

if (typeof module !== 'undefined' && module.exports) {
  module.exports = { formatDate, timeDiff, deepClone, Validators };
}
if (typeof window !== 'undefined') {
  window.Utils = { formatDate, timeDiff, deepClone, Validators };
}